package com.lagou.edu.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @ClassName: MyClassLoader
 * @Auther: Jerry
 * @Date: 2020/8/4 16:55
 * @Desctiption: TODO
 * @Version: 1.0
 */
public class MyClassLoader extends ClassLoader {

    private String location;

    public String getLocation() {
        return location;
    }

    public MyClassLoader(String location) {
        this.location = location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 获取该class文件字节码数组
        Class clazz = null;

        byte[] bytes = getClassData(location);

        if (bytes != null) {
            clazz = defineClass(name, bytes,0, bytes.length);
        }
        return clazz;
    }

    private byte[] getClassData(String location) {
        File file = new File(location);
        if (file.exists() && file.isFile()) {
            FileInputStream fis = null;
            ByteArrayOutputStream bos = null;
            try {
                fis = new FileInputStream(file);
                bos = new ByteArrayOutputStream();

                byte[] bytes = new byte[1024];
                int size = 0;
                while ((size = fis.read(bytes)) != -1){
                    bos.write(bytes, 0, size);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return bos.toByteArray();
        }
        return null;
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
            InstantiationException {
        MyClassLoader myClassLoader1 = new MyClassLoader("C:\\Users\\webapps\\demo1\\server");
        Class<?> aClass1 = myClassLoader1.loadClass("server.LagouServlet");
        Object o1 = aClass1.newInstance();

        MyClassLoader myClassLoader2 = new MyClassLoader("C:\\Users\\webapps\\demo2\\server");
        Class<?> aClass2 = myClassLoader1.loadClass("server.LagouServlet");
        Object o2 = aClass2.newInstance();
        System.out.println(o1 == o2);
    }
}
